3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

  1. For example, given array S = {-1 2 1 -4}, and target = 1.
  2. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Solution:

  1. public class Solution {
  2. public int threeSumClosest(int[] num, int target) {
  3. Arrays.sort(num);
  4. int n = num.length;
  5. int closest = num[0] + num[1] + num[2];
  6. for (int i = 0; i < n - 2; i++) {
  7. int j = i + 1;
  8. int k = n - 1;
  9. while (j < k) {
  10. int sum = num[i] + num[j] + num[k];
  11. if (sum == target) {
  12. return sum;
  13. } else if (sum < target) {
  14. j++;
  15. } else {
  16. k--;
  17. }
  18. if (Math.abs(target - sum) < Math.abs(target - closest)) {
  19. closest = sum;
  20. }
  21. }
  22. }
  23. return closest;
  24. }
  25. }

Time complexity: O(n^2)